﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using LibCommon;
using RTCCore;

namespace LibRTC.Core.MessageMap.MessagingEvent
{
    internal delegate void MessagingDelegate(string remoteUserName, string remoteUserURI,
                                    string messageHeader, string messageBody);

    internal delegate void UserStatusDelegate(string remoteUserName, string remoteUserURI,RTC_MESSAGING_USER_STATUS userStatus);

    public class MessagingHandler : SimpleMessageHandler,IMessagingRegister
    {
        private static ILogger LOGGER = LoggerFactory.GetLogger("MessagingHandler", null);

        private MessagingDelegate _messageDelegate;
        private UserStatusDelegate _userStatusDelegate;

        public MessagingHandler() {
            _rtcEvent = RTC_EVENT.RTCE_MESSAGING;
            _name = "MessagingHandler";
        }

        public void Register(IMessagingUI clientInterface)
        {
            Debug.Assert(null != clientInterface);
            _messageDelegate += clientInterface.OnMessaging;
            _userStatusDelegate += clientInterface.OnUserStatus;
        }

        public void UnRegister(IMessagingUI clientInterface)
        {
            Debug.Assert(null != clientInterface);
            _messageDelegate -= clientInterface.OnMessaging;
            _userStatusDelegate -= clientInterface.OnUserStatus;
        }

        public override void Process(RTC_EVENT rtcEventType, object rtcEvent)
        {
            Debug.Assert(RTC_EVENT.RTCE_MESSAGING == rtcEventType);
            Debug.Assert(null != rtcEvent);
            Debug.Assert(rtcEvent is IRTCMessagingEvent);
            
            IRTCMessagingEvent messagingEvent = (IRTCMessagingEvent) rtcEvent;

            LOGGER.LogDebug("Messaging Event" + messagingEvent.EventType);

            //first, get the participant
            IRTCParticipant participant = messagingEvent.Participant;
            Debug.Assert(null != participant);

            switch (messagingEvent.EventType)
            {
                case RTC_MESSAGING_EVENT_TYPE.RTCMSET_STATUS:
                    
                    if(null != _userStatusDelegate) {
                        _userStatusDelegate(participant.Name,participant.UserURI,messagingEvent.UserStatus);
                    }

                    break;

                case RTC_MESSAGING_EVENT_TYPE.RTCMSET_MESSAGE:

                    if(null != _messageDelegate) {
                        _messageDelegate(participant.Name,participant.UserURI,messagingEvent.MessageHeader,messagingEvent.Message);
                    }

                    break;

                default:
                    // this should never happen
                    LOGGER.LogError("Wrong Message Type : " + messagingEvent.EventType);
                    break;
            }
        }

    }
}
